<!-- src/views/Admin/FA_review.vue -->
<template>
  <div class="fa-review">
    <div class="page-header">
      <h2>融资申请审核</h2>
      <el-button @click="fetchData">刷新</el-button>
    </div>

    <el-table :data="applications" border style="width: 100%" table-layout="auto">
      <el-table-column prop="username" label="申请人" width="90" align="center" />
      <el-table-column prop="amount" label="金额(元)" width="100" align="center">
        <template #default="scope">
          {{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column prop="purpose" label="用途" min-width="120" />
      <el-table-column prop="term" label="期限(月)" width="80" align="center" />
      <el-table-column prop="interestRate" label="年利率(%)" width="90" align="center" />
      <el-table-column prop="applyTime" label="申请时间" width="160" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.applyTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="90" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditOpinion" label="审核意见" min-width="120" show-overflow-tooltip />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="scope">
          <!-- 1. 待审核（status=0）：显示【通过】【拒绝】按钮 -->
          <template v-if="scope.row.status === 0">
            <el-button size="small" type="success" @click="handleApprove(scope.row)">
              通过
            </el-button>
            <el-button size="small" type="danger" @click="handleReject(scope.row)" style="margin-left: 5px;">
              拒绝
            </el-button>
          </template>

          <!-- 2. 审核通过（status=1）：显示【放款】按钮 -->
          <el-button
              v-else-if="scope.row.status === 1"
              size="small"
              type="primary"
              @click="handleDisburse(scope.row)"
          >
            放款
          </el-button>

          <!-- 3. 已放款（status=3）：显示【还款】按钮 -->
          <el-button
              v-else-if="scope.row.status === 3"
              size="small"
              type="success"
              @click="handleRepay(scope.row)"
          >
            还款
          </el-button>

          <!-- 4. 其他状态：不显示任何按钮 -->
          <template v-else>
            <span>-</span> <!-- 用"-"占位，避免操作列空荡 -->
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核意见对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item :label="opinionLabel">
          <el-input 
            v-model="form.opinion" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOpinion">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllFinanceApplications,
  approveApplication,
  rejectApplication,
  disburseApplication,
  repayApplication
} from '@/apis/admin.js'

const applications = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const opinionLabel = ref('')
const currentRow = ref(null)
const currentAction = ref('') // 'approve', 'reject', 'disburse', 'repay'

const form = reactive({
  opinion: ''
})

// 格式化日期时间
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const fetchData = async () => {
  try {
    const response = await getAllFinanceApplications()
    if (response.code === 200) {
      applications.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

const handleApprove = (row) => {
  currentRow.value = row
  currentAction.value = 'approve'
  dialogTitle.value = '通过申请'
  opinionLabel.value = '通过意见'
  form.opinion = '审核通过'
  dialogVisible.value = true
}

const handleReject = (row) => {
  currentRow.value = row
  currentAction.value = 'reject'
  dialogTitle.value = '拒绝申请'
  opinionLabel.value = '拒绝原因'
  form.opinion = '审核拒绝'
  dialogVisible.value = true
}

const handleDisburse = (row) => {
  currentRow.value = row
  currentAction.value = 'disburse'
  dialogTitle.value = '放款确认'
  opinionLabel.value = '放款备注'
  form.opinion = '已放款'
  dialogVisible.value = true
}

const handleRepay = (row) => {
  currentRow.value = row
  currentAction.value = 'repay'
  dialogTitle.value = '还款确认'
  opinionLabel.value = '还款备注'
  form.opinion = '已还款'
  dialogVisible.value = true
}

const submitOpinion = async () => {
  try {
    let response
    const financeId = currentRow.value.finance_id
    const opinion = form.opinion

    switch (currentAction.value) {
      case 'approve':
        response = await approveApplication(financeId, opinion)
        break
      case 'reject':
        response = await rejectApplication(financeId, opinion)
        break
      case 'disburse':
        response = await disburseApplication(financeId, opinion)
        break
      case 'repay':
        response = await repayApplication(financeId, opinion)
        break
      default:
        ElMessage.error('未知操作')
        return
    }

    if (response.code === 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      fetchData() // 刷新列表
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const getStatusText = (status) => {
  const map = {
    0: '待审核', 
    1: '审核通过', 
    2: '已拒绝', 
    3: '已放款',
    4: '已还款',
    5: '逾期',
    6: '已取消'
  }
  return map[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    0: '',           // 待审核 - 默认灰色
    1: 'success',    // 审核通过 - 绿色
    2: 'danger',     // 已拒绝 - 红色
    3: 'primary',    // 已放款 - 蓝色
    4: 'success',    // 已还款 - 绿色
    5: 'warning',    // 逾期 - 橙色
    6: 'info'        // 已取消 - 灰色
  }
  return typeMap[status] || 'info'
}

fetchData()
</script>

<style scoped>
.fa-review {
  width: 100%;
  height: auto;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 可选：给操作列的"-"占位符加样式，使其居中更协调 */
.el-table .cell span:empty + span {
  color: #999;
}
</style>